<?php
/**
 * @Author: Ron Chen
 * @Date:   2017-03-11 21:45:57
 * @Last Modified by:   Ron Chen
 * @Last Modified time: 2018-01-24 23:01:50
 */
namespace api\controllers;

use Yii;

use yii\web\Response;
use yii\helpers\Html;
use yii\helpers\Json;
use yii\helpers\Url;
use common\models\AccountWechat;
use common\helpers\StringHelper;
use common\services\config\Config;

/**
 * Base controller
 */
abstract class BaseController extends \common\bases\BaseController
{
	public $enableCsrfValidation = false;
    public $user_id; 

	public function init()
	{
		parent::init();
		if ($this->request->get('callback')) {
			$this->getResponse()->format = Response::FORMAT_JSONP;
		} else {
			$this->getResponse()->format = Response::FORMAT_JSON;
		}
        if (!$this->user_id) {
            return $this->check();
        }
        $this->check();
        // $this->getUserId();
	}

    public function getUserId(){
        $token   = $this->request->get('token','');
        if ($token) {
            $this->user_id = StringHelper::decrypt($token);
        }else{
            $this->user_id = 0;
        }
    }

    public function check(){
        // 未登录Wechat
        $user_id = \Yii::$app->session['uid'];
        if ($user_id) {
            $user_info = AccountWechat::find()->where(['ff_id' => $user_id])->limit(1)->one();
            if (!$user_info) {
                return $this->errorResult(Config::$notLogin);
            }
        }else{
            return $this->errorResult(Config::$notLogin);
        }
        // todo:处理这个系统的用户表
        $this->user_id = $user_id;
    }

	/**
	 * JSON 返回值处理
	 */	
	public function returnResponse($code=0,$message='success',$data=[]){
		// 针对成功返回的简单处理
		if (is_array($code) && $code) {
            $data    = $code;
			$message = "success";
            $code    = 0;
        }
		return [
			"code"    => $code,
			"message" => $message,
			"data"    => $data,
		];
	}

    /**
     * Json 处理
     * @param $data
     * @param string $message
     * @param string $code
     * @return array
     */
    public function endReponse($code='0',$data,$message='Success'){
        if (is_array($data)) {
            return [
                "code" => $code,
                "message" => $message,
                "data" => $data,
            ];
        }else{
            return [
                "code" => $code,
                "message" => $data,
            ];
        }
    }

    /**
     * 错误结果返回
     * @param $data
     * @return array
     */
    public function errorResult($data = null){
        if(is_array($data)){
            return $data;
        }else{
            return [
                "code" => 404,
                "message" => '服务器繁忙，请稍后再试！',
            ];
        }
    }
}